import secrets
import hmac
import functools
from flask import jsonify, request


secrets = 'rfcfer2'


def generate_token(username):
    if username is None:
        return ""
    token = hmac.new(key=secrets.encode('utf-8'), msg = username.encode('utf-8'), digestmod = 'sha1').hexdigest()
    return token


def certify_token(username, token):
    val_token = generate_token(username)
    if val_token == token:
        return True
    else:
        return False 


# 装饰器
def require_token(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get('token')
        if certify_token(username=request.headers.get('username'), token=token):
            return func(*args, **kwargs)
        else:
            return jsonify(code=503, msg='token验证失败')
    return wrapper


if __name__ == '__main__':
    token = generate_token('zhangsan')
    print(token)
    print(certify_token('zhangsan', token))